<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 面包屑 -->
        <el-breadcrumb
          v-if="$route.query.name !== undefined"
          separator-class="el-icon-arrow-right"
          class="clearfix"
        >
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ $route.query.name }}</el-breadcrumb-item>
          <el-breadcrumb-item>目录列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 目录名称 -->
        <el-form
          :inline="true"
          ref="form"
          :model="form"
          label-width="80px"
          size="small"
        >
          <el-form-item label="目录名称">
            <el-input v-model="form.directoryName"></el-input>
          </el-form-item>

          <!-- 状态输入框 -->
          <el-form-item label="状态">
            <el-select v-model="form.state" placeholder="请选择">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>

          <!-- 按钮 -->
          <el-button size="small" @click="clearFn">清除</el-button>
          <el-button type="primary" size="small" @click="searchFn"
            >搜索</el-button
          >
          <!-- 返回学科按钮 -->
          <el-button
            v-if="$route.query.id !== undefined"
            @click="returnSubject"
            type="text"
            style="margin-left: 742px"
          >
            <i class="el-icon-back"></i>
            返回学科
          </el-button>

          <el-button
            type="success"
            size="small"
            class="addDirectory"
            @click="addDirectorys"
            ><i class="el-icon-edit"></i> 新增目录</el-button
          >
        </el-form>

        <!-- 消息提示的文案 -->
        <el-alert
          :title="`数据一共${counts}条`"
          type="info"
          show-icon
          :closable="false"
        >
        </el-alert>

        <!-- 学科目录表格 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科" width="180">
          </el-table-column>
          <el-table-column prop="directoryName" label="目录名称">
          </el-table-column>
          <el-table-column prop="username" label="创建者"> </el-table-column>

          <el-table-column label="创建日期">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | parseTimeByString }} </span>
            </template>
          </el-table-column>

          <el-table-column prop="totals" label="面试题数量"> </el-table-column>
          <el-table-column prop="state" label="状态" :formatter="formatter">
          </el-table-column>
          <el-table-column prop="operate" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="Enable(scope.row)">
                {{ scope.row.state === 0 ? "启用" : "禁用" }}
              </el-button>
              <el-button
                type="text"
                size="small"
                :disabled="scope.row.state ? !isDone : isDone"
                @click="reviseDirectory(scope.row)"
                >修改</el-button
              >
              <el-button
                type="text"
                size="small"
                :disabled="scope.row.state ? !isDone : isDone"
                @click="delDirectory(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          background
          layout="prev, pager, next,sizes, jumper"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="query.pagesize"
          :current-page="query.page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :total="counts"
        >
        </el-pagination>

        <!-- 新增目录弹框 -->
        <el-dialog
          :title="isEdit ? '修改目录' : '新增目录'"
          :visible.sync="showDialog"
          width="20%"
          destroy-on-close
          v-if="showDialog"
          @close="addCancel"
        >
          <!--  新增目录 -->
          <el-form
            ref="direform"
            :model="direform"
            label-width="80px"
            :rules="rules"
          >
            <el-form-item label="所属学科" size="small" prop="region">
              <el-select v-model="direform.subjectID" placeholder="请选择学科">
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in disciplineList"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="目录名称" size="small" prop="directoryName">
              <el-input
                v-model="direform.directoryName"
                style="width: 82%"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="addCancel">取 消</el-button>
              <el-button type="primary" @click="addSubmit">确 定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list as getCompanys } from '@/api/hmmm/companys'
import { list as getQuestion } from '@/api/hmmm/questions'
import {
  list,
  add,
  update,
  remove,
  changeState
} from '@/api/hmmm/directorys.js'
import { status } from '@/api/hmmm/constants.js'
import { simple } from '@/api/hmmm/subjects.js'
export default {
  name: 'ssss',
  created () {
    getCompanys()
    getQuestion()
    // 调用获取目录列表方法
    this.getAListOfDirectory()
    // 调用获取学科列表的方法
    this.getsubjectList()
  },
  data () {
    return {
      form: {
        directoryName: null, // 目录名称输入值
        state: null // 状态下拉列表值
      },
      // 目录列表
      tableData: [],
      query: {
        page: 1, // 当前页面
        pagesize: 10 // 页面显示的条数
      },
      counts: 0, // 角色数据总条数
      showDialog: false, // 控制新增目录弹框显示与隐藏
      direform: {
        directoryName: '', // 目录名称
        subjectID: '' // 学科id
      },
      rules: {
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ],
        subjectID: [
          { required: true, message: '请输入所属学科', trigger: 'blur' }
        ]
      },
      disciplineList: [], // 学科列表
      isEdit: false, // 是否修改状态
      dirId: null, // 修改ID
      isDone: false // 启用\禁用切换
    }
  },
  methods: {
    // 返回学科按钮
    returnSubject () {
      this.$router.back()
    },

    // 启用\禁用
    async Enable (row) {
      if (row.state === 1) {
        row.state = 0
        await changeState(row, row.state)
        this.$message.success('切换成功')
      } else if (row.state === 0) {
        row.state = 1
        await changeState(row, row.state)
        this.$message.success('切换成功')
      }
    },

    // 清除
    clearFn () {
      this.form = {}
      this.getAListOfDirectory()
    },

    // 搜索
    searchFn () {
      this.getAListOfDirectory()
    },

    // 删除角色
    async delDirectory (row) {
      // 显示删除询问对话框
      const delRes = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 用户点击了取消，给用户进行提示
      if (delRes === 'cancel') return this.$message.info('您取消了删除')
      // 调用删除的 API
      await remove(row)

      // 删除角色的分页异常处理
      // 判断当前数据的长度是否等于 1
      if (this.tableData.length === 1) {
        this.query.page--
        // 如果是第一页的第一条
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }
      // 删除成功后的提示
      this.$message.success('删除成功')
      // 重新获取数据
      this.getAListOfDirectory()
    },

    // 修改目录
    reviseDirectory (row) {
      this.dirId = row.id
      // 弹框展示
      this.showDialog = true
      // 设置是否是修改
      this.isEdit = true
      // 数据回显
      this.direform.directoryName = row.directoryName
      this.direform.subjectID = row.subjectID
    },

    // 添加目录
    addDirectorys () {
      // 控制弹框展示
      this.showDialog = true
      this.isEdit = false
    },

    // 添加/修改目录确认按钮
    addSubmit () {
      // 兜底验证
      this.$refs.direform.validate(async (valid) => {
        if (valid) {
          this.isEdit ? this.editDir() : this.addDir()
        }
      })
    },

    // 添加目录
    async addDir () {
      // 调接口
      await add({
        subjectID: this.direform.subjectID,
        directoryName: this.direform.directoryName
      })
      // 告诉用户添加成功
      this.$message.success('添加成功')
      // 关闭新增目录组件的展示
      this.showDialog = false
      // 清空表单数据
      this.direform = {}
      // 重新调用获取目录数据
      this.getAListOfDirectory()
    },

    // 修改目录
    async editDir () {
      // 调接口
      await update({ id: this.dirId, ...this.direform })
      // 告诉用户修改完成
      this.$message.success('修改完成')
      // 重新获取列表数据
      this.getAListOfDirectory()
      // 关闭弹框
      this.showDialog = false
    },

    // 取消添加按钮
    addCancel () {
      this.showDialog = false
      this.direform = {}
    },

    // 枚举状态
    formatter (row, column, cellValue, index) {
      // 用数组的 find 方法找到 id = 1 的元素，再取出它的 value
      const obj = status.find((item) => item.value === cellValue)
      return obj ? obj.label : '未知'
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange (newSize) {
      this.query.pagesize = newSize
      this.getAListOfDirectory()
    },

    // 当前页面发生改变时触发
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.getAListOfDirectory()
    },

    // 获取学科列表
    async getsubjectList () {
      const res = await simple()
      this.disciplineList = res.data
    },

    // 获取目录列表
    async getAListOfDirectory () {
      if (
        this.$route.fullPath !== undefined &&
        this.$route.query.id !== undefined
      ) {
        this.query.subjectID = this.$route.query.id
      }
      const res = await list({ ...this.query, ...this.form })
      this.tableData = res.data.items
      this.counts = res.data.counts
    }
  },
  beforeRouteUpdate (to, form, next) {
    this.$nextTick(() => {
      if (to.fullPath === '/subjects/directorys') {
        this.query.subjectID = null
        this.getAListOfDirectory(this.query)
      }
    })
  }
}
</script>

<style scoped>
.addDirectory {
  float: right;
}
.el-alert {
  margin-bottom: 10px;
}
.el-pagination {
  float: right;
}
.clearfix {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgb(199, 199, 199);
}
</style>
